package cn.tedu.boyou.website.param;

import cn.tedu.boyou.cache.prefix.UserInfoKeyPrefix;
import cn.tedu.boyou.cache.service.IUserInfoRedisService;
import cn.tedu.boyou.member.domain.UserInfo;
import cn.tedu.boyou.website.annotation.UserParam;
import cn.tedu.boyou.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
//请求映射方法注入自定义请求参数
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver{
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    //进行解析时使用的支持解析的参数类型
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //支持解析参数类型
        //只有return true 才执行下面解析方法resolveArgument
        return methodParameter.hasParameterAnnotation(UserParam.class) &&  methodParameter.getParameterType() == UserInfo.class;
    }

    //这个方法返回值，会注入到请求映射方法中，形式参数类型为Userinfo 这个对象里面
    /**
     * userInfo = resolveArgument(...)
     * public Object userIbfo(HttpServletRequest request, UserInfo userInfo){...}
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        //获取请求对象
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);

        Cookie c = CookieUtil.getCookie(request, UserInfoKeyPrefix.TOKEN_COOKIE_NAME);

        UserInfo userInfo = null;
        if(c != null){
            //从redis中获取token 对应的用户对象
            userInfo = userInfoRedisService.getUserInfoByToken(UserInfoKeyPrefix.USER_INFO_TOKEN,c.getValue());
        }
        return userInfo;
    }
}
